package com.zaofan.service;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.rowset.serial.SerialException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.Lable;
import com.zaofan.bean.OpenArea;
import com.zaofan.bean.OpenBuilder;
import com.zaofan.bean.OpenCity;
import com.zaofan.bean.Shop;
import com.zaofan.bean.ShopBuilder;
import com.zaofan.bean.ShopPayLable;
import com.zaofan.constant.StateConstant;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.ProductDao;
import com.zaofan.dao.ShopDao;
import com.zaofan.mobile.bean.SpecialShop;
import com.zaofan.utils.C3p0DataSourceUtils;

public class ShopService {
	private ShopDao shopDao = new ShopDao();
	private OpenCityService cityService = new OpenCityService();
	private OpenAreaService areaService = new OpenAreaService();
	private OpenBuilderService builderService = new OpenBuilderService();
	private LableService lableService = new LableService();
	private ShopPayLableService payService = new ShopPayLableService();
	private ShopBuilderService shopBuilderService = new ShopBuilderService();
	private ProductDao productDao = new ProductDao();

	public void delete(Shop shop) {
		shopDao.del(shop);
	}

	public void add(Shop shop, String[] payLableId, String[] builderIds) {
		shop.setAddTime(new Date());
		// 添加基本信息
		OpenCity city = cityService.findById(shop.getCityId());
		shop.setCityName(city.getCityName());
		OpenArea area = areaService.findById(shop.getAreaId());
		if (shop.getCoverType() == StateConstant.COVER_TYPE_BUILDER) {
			shop.setAreaName(area.getAreaName());
		}
		Lable lable = lableService.findById(shop.getLableId());
		shop.setLableName(lable.getName());
		lable = lableService.findById(shop.getExpressLableId());
		shop.setExpressLableName(lable.getName());
		lable = lableService.findById(shop.getShowLableId());
		shop.setShowLableName(lable.getName());
		shop.setShowLableCode(lable.getCode());
		int shopId = shopDao.addShop(shop);
		if (shopId != 0) {
			if (shop.getCoverType() == StateConstant.COVER_TYPE_BUILDER) {
				area.setShopNum(area.getShopNum() + 1);
				areaService.update(area);
			}
			city.setShopNum(city.getShopNum() + 1);
			cityService.update(city);
			if (payLableId != null) {
				ShopPayLable pay = null;
				Integer id;
				for (String item : payLableId) {
					id = Integer.valueOf(item);
					lable = lableService.findById(id);
					pay = new ShopPayLable();
					pay.setShopId(shopId);
					pay.setLableId(id);
					pay.setLableName(lable.getName());
					payService.add(pay);
				}
			}
			if (shop.getCoverType() == StateConstant.COVER_TYPE_BUILDER) {
				if (builderIds != null) {
					ShopBuilder builder = null;
					OpenBuilder openBuilder = null;
					Integer id;
					for (String item : builderIds) {
						id = Integer.valueOf(item);
						openBuilder = builderService.findById(id);
						builder = new ShopBuilder();
						builder.setBuilderId(id);
						builder.setShopId(shopId);
						builder.setBuilderName(openBuilder.getBuilderName());
						shopBuilderService.add(builder);
					}
				}
			}
		}
	}

	public void update(Shop shop, String[] payLableId, String[] builderIds) {
		OpenCity city = cityService.findById(shop.getCityId());
		shop.setCityName(city.getCityName());
		OpenArea area = areaService.findById(shop.getAreaId());
		if (shop.getCoverType() == StateConstant.COVER_TYPE_BUILDER) {
			shop.setAreaName(area.getAreaName());
		}
		Lable lable = lableService.findById(shop.getLableId());
		shop.setLableName(lable.getName());
		lable = lableService.findById(shop.getExpressLableId());
		shop.setExpressLableName(lable.getName());
		lable = lableService.findById(shop.getShowLableId());
		shop.setShowLableName(lable.getName());
		shop.setShowLableCode(lable.getCode());
		shopDao.update(shop);
		int shopId = shop.getId();
		if (shopId != 0) {
			if (payLableId != null) {
				payService.deleteByShopId(shopId);
				ShopPayLable pay = null;
				Integer id;
				for (String item : payLableId) {
					id = Integer.valueOf(item);
					lable = lableService.findById(id);
					pay = new ShopPayLable();
					pay.setShopId(shopId);
					pay.setLableId(id);
					pay.setLableName(lable.getName());
					payService.add(pay);
				}
			}
			if (shop.getCoverType() == StateConstant.COVER_TYPE_BUILDER) {
				if (builderIds != null) {
					shopBuilderService.deleteByShopId(shopId);
					ShopBuilder builder = null;
					OpenBuilder openBuilder = null;
					Integer id;
					for (String item : builderIds) {
						id = Integer.valueOf(item);
						openBuilder = builderService.findById(id);
						builder = new ShopBuilder();
						builder.setBuilderId(id);
						builder.setShopId(shopId);
						builder.setBuilderName(openBuilder.getBuilderName());
						shopBuilderService.add(builder);
					}
				}
			}
		}
	}

	public List<Shop> findAll(Map<String, Object> params) {
		List<Shop> data = shopDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return shopDao.count(params);
	}

	public Shop findById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		return shopDao.findOne(params);
	}

	public void setShopState(Shop shop) {
		shopDao.setShopState(shop);
		OpenCity city = cityService.findById(shop.getCityId());
		OpenArea area = areaService.findById(shop.getAreaId());
		if (shop.getState() == StateConstant.STATE_SHOW) {
			city.setShopNum(city.getShopNum() + 1);
			if (area != null) {
				area.setShopNum(area.getShopNum() + 1);
			}

		} else {
			city.setShopNum(city.getShopNum() - 1);
			if (area != null) {
				area.setShopNum(area.getShopNum() - 1);
			}

		}
		cityService.update(city);
		if (area != null) {
			areaService.update(area);
		}

	}

	public List<Shop> findByCoverType(int type) {
		Map<String, Object> params = new HashMap<>();
		params.put("coverType", type);
		return findAll(params);
	}

	@SuppressWarnings("unchecked")
	public List<SpecialShop> findSpecial(int type) {
		try {
			String sql = "select * from shop where coverType = 1 and state = " + StateConstant.STATE_SHOW
					+ " order by sort asc";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
			List<Shop> shops = runner.query(sql, new BeanListHandler<>(Shop.class));
			List<SpecialShop> datas = new ArrayList<>();
			SpecialShop item = null;
			for (Shop shop : shops) {
				item = new SpecialShop();
				BeanUtils.copyProperties(item, shop);
				if (shop.getIsOpen() == 1) {
					item.setShopImage(UrlConstant.HOST_URL + shop.getShopImage());
				} else {
					item.setShopImage(UrlConstant.HOST_URL + shop.getCloseImage());
				}
				datas.add(item);
			}
			return datas;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	@SuppressWarnings("unchecked")
	public List<com.zaofan.mobile.bean.Shop> getTop10Shop() {
		try {
			String sql = "select * from shop where coverType = 0 and state = " + StateConstant.STATE_SHOW
					+ " order by sort asc limit 0,10";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
			List<Shop> shops = runner.query(sql, new BeanListHandler<>(Shop.class));
			List<com.zaofan.mobile.bean.Shop> datas = new ArrayList<>();
			com.zaofan.mobile.bean.Shop shop;
			try {
				for (Shop s : shops) {
					shop = new com.zaofan.mobile.bean.Shop();
					BeanUtils.copyProperties(shop, s);
					shop.setShopImage(UrlConstant.HOST_URL + shop.getShopImage());
					if (shop.getIsOpen() == 1) {
						shop.setCloseImage(UrlConstant.HOST_URL + shop.getCloseImage());
					}
					datas.add(shop);
				}
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}

			return datas;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	@SuppressWarnings("unchecked")
	public List<Shop> findByBuilderId(Integer builderId) {
		try {
			String sql = "select * from shop where coverType = 0 and state = " + StateConstant.STATE_SHOW
					+ " and id in ( select shopId from shopbuilder where builderId = " + builderId + " ) order by sort";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
			List<Shop> shops = runner.query(sql, new BeanListHandler<>(Shop.class));
			for (Shop shop : shops) {
				shop.setShopImage(UrlConstant.HOST_URL + shop.getShopImage());
				if (shop.getIsOpen() == 1) {
					shop.setCloseImage(UrlConstant.HOST_URL + shop.getCloseImage());
				}
			}
			return shops;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	public Long countByBuilderId(Integer builderId) {
		try {
			String sql = "select count(*) from shop where coverType = 0 and state = " + StateConstant.STATE_SHOW
					+ " and id in ( select shopId from shopbuilder where builderId = " + builderId + " ) order by sort";
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
			return runner.query(sql, new ScalarHandler<Long>());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0L;
	}

	public List<Shop> findByBuilderIdWithPage(String builderId, String begin, String end) throws SerialException {
		try {
			Integer.valueOf(builderId);
			Integer.valueOf(begin);
			Integer.valueOf(end);
		} catch (Exception e) {
			throw new SerialException("参数错误!!!");
		}
		try {
			String sql = "select * from shop where coverType = 0 and state = " + StateConstant.STATE_SHOW
					+ " and id in ( select shopId from shopbuilder where builderId = " + builderId
					+ " ) order by sort limit " + begin + "," + end;
			System.err.println(sql);
			QueryRunner runner = new QueryRunner(C3p0DataSourceUtils.getDataSource());
			List<Shop> shops = runner.query(sql, new BeanListHandler<>(Shop.class));
			for (Shop shop : shops) {
				shop.setShopImage(UrlConstant.HOST_URL + shop.getShopImage());
				if (shop.getIsOpen() == 1) {
					shop.setCloseImage(UrlConstant.HOST_URL + shop.getCloseImage());
				}
			}
			return shops;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return Collections.EMPTY_LIST;
	}

	public Shop getPackageShop(String showType) {
		Map<String, Object> params = new HashMap<>();
		params.put("showLableCode", showType);
		return shopDao.findOne(params);
	}

	public Shop findByProductId(Integer productId) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", productId);
		Integer shopId = productDao.findOne(params).getShopId();
		return findById(shopId);
	}

}
